package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.InventoryListBoxAdapter;
import com.mflex.WHSmartWhouseAd.adapter.TaskOrderBoxAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitSamplinginspectionModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.QMSInventoryDetailsPdaInfo;
import com.mflex.WHSmartWhouseAd.model.SpotCheckPdaInfor;
import com.mflex.WHSmartWhouseAd.utils.HideKeyBoardUtil;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class RawMaterialSpotCheckActivity extends BaseActivity implements AdapterView.OnItemClickListener  {
    // 料号
    EditText stvPartNo;
    // 任务单号
    EditText stvTask;
    // 抽检人员
    EditText stvSamplingPersonnel;
    // 箱号
    EditText stvBoxNo;
    // 需求数量
    EditText stvQuantityRequired;
    // 扫描数量
    EditText stvActualScanNumber;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    // 提交
    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<QMSInventoryDetailsPdaInfo> QMSInventoryDetailsModelList=new ArrayList<>();
    CommitSamplinginspectionModel model = new CommitSamplinginspectionModel();

    private String userName;
    private String MaterialType;
    private String BatchNo;
    private String ActualQuantityRequired;//需求数量
    private double ActualScanNumber=0;//累加数量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_row_material_spot_check);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
        //        id绑定
        stvPartNo = findViewById(R.id.stv_PartNo);
        stvTask = findViewById(R.id.stv_Task);
        stvSamplingPersonnel = findViewById(R.id.stv_SamplingPersonnel);
        stvBoxNo = findViewById(R.id.stv_BoxNo);
        stvQuantityRequired = findViewById(R.id.stv_QuantityRequired);
        stvActualScanNumber = findViewById(R.id.stv_ActualScanNumber);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");

        // 视图按键监听器
        buttonSubmit.setOnClickListener(this);
        stvBoxNo.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        // 获取查询界面传过来的参数
        stvTask.setText(intent.getStringExtra("TaskNo"));
        stvPartNo.setText(intent.getStringExtra("MPart"));
        MaterialType = intent.getStringExtra("MaterialType");
        BatchNo =  intent.getStringExtra("BatchLot");
        ActualQuantityRequired = intent.getStringExtra("NeedQty");
        stvQuantityRequired.setText(String.valueOf(ActualQuantityRequired));//需求数量
        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));//扫描数量

        stvBoxNo.requestFocus();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                QMSInventoryDetailsModelList.clear();
                InventoryListBoxAdapter InventoryListBoxAdapter = new InventoryListBoxAdapter(RawMaterialSpotCheckActivity.this,QMSInventoryDetailsModelList);
                lvList.setAdapter(InventoryListBoxAdapter);
                stvBoxNo.setText("");
                ActualScanNumber = 0;
                stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNo: // 箱号
                     chekBoxNo();
                    break;
                default:
                    break;
            }
        }
        return false;
    }
//    箱号回车事件触发接口
    private void chekBoxNo() {
        if(StringUtils.isEmpty(stvBoxNo.getText().toString())) {
            return;
        }
        // 累加数量不能大于需求数量
        int num=(int)Math.round(Double.parseDouble(ActualQuantityRequired));
        if(ActualScanNumber > num) {
            MediaPlayer mp = MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("超出需求数量！")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        //      测试
//        QMSInventoryDetailsPdaInfo people = new QMSInventoryDetailsPdaInfo();
//        double adm =   Math.random();
//        people.setReelId("123"+adm);
//        people.setLocName("库位");
//        people.setERPLot("jdelot");
//        people.setMPart("料号");
//        people.setQty("20");
//        ActualScanNumber +=Double.parseDouble(people.getQty());
//        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
//
//        QMSInventoryDetailsModelList.add(people);
//        InventoryListBoxAdapter InventoryListBoxAdapter = new InventoryListBoxAdapter(RawMaterialSpotCheckActivity.this,QMSInventoryDetailsModelList);
//
//        lvList.setAdapter(InventoryListBoxAdapter);

//      结束
        boolean ischeck = true;
        // 重复扫描卡控
        if(!QMSInventoryDetailsModelList.isEmpty()) {
            for(QMSInventoryDetailsPdaInfo item: QMSInventoryDetailsModelList) {
                if(Objects.equals(item.getReelId(), stvBoxNo.getText().toString())) {
                    ischeck = false;
                    break;
                }
            }
        }
        if(!ischeck) {
            MediaPlayer mp = MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("箱号"+stvBoxNo.getText().toString()+"在列表中已存在")
                    .positiveText(R.string.lab_submit)
                    .show();
            stvBoxNo.setText("");
            stvBoxNo.requestFocus();
            return;

        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/GetInventoryDetails")
                .params("ReelId",stvBoxNo.getText().toString())
                .params("TaskNo",stvTask.getText().toString())
              //  .params("ErpLot",BatchNo)
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<List<QMSInventoryDetailsPdaInfo>>() {
                    @Override
                    public  void  onSuccess(List<QMSInventoryDetailsPdaInfo> response) {
                        miniLoadingDialog.dismiss();
                        // 循环添加箱号数据
                        for(QMSInventoryDetailsPdaInfo item : response) {
                            ActualScanNumber +=Double.parseDouble(item.getQty());

                            QMSInventoryDetailsModelList.add(item);

                        }

                        InventoryListBoxAdapter InventoryListBoxAdapter = new InventoryListBoxAdapter(RawMaterialSpotCheckActivity.this,QMSInventoryDetailsModelList);
                        lvList.setAdapter(InventoryListBoxAdapter);
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvBoxNo.setText("");
                        stvBoxNo.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });

    }
    private void saveButtonMd(View v) {
//        int num=(int)Math.round(Double.parseDouble(ActualQuantityRequired));
//        if(ActualScanNumber < num) {
//            MediaPlayer mp = MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
//            new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("缺少需求数量！")
//                    .positiveText(R.string.lab_submit)
//                    .show();
//            return;
//        }
        if(StringUtils.isEmpty(stvSamplingPersonnel.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("请输入抽检人员")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        List<CommitSamplinginspectionModel> dataList = new ArrayList<>();
        for( QMSInventoryDetailsPdaInfo item : QMSInventoryDetailsModelList) {
            CommitSamplinginspectionModel entity= new CommitSamplinginspectionModel();
            entity.setTaskNo(stvTask.getText().toString());
            entity.setVehicleNumber(item.getVehNo());
            entity.setReelId(item.getReelId());
             entity.setMType(item.getMType());
            entity.setERPlot(item.getERPLot());
            entity.setMPart(item.getMPart());
            entity.setUser(stvSamplingPersonnel.getText().toString());
            dataList.add(entity);
        }
        CommonRequest request =new CommonRequest();
        request.setJson(JsonUtil.toJson(dataList));
        String json = JsonUtil.toJson(dataList);
      miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/CommitQMSInspectionData")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(150000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        QMSInventoryDetailsModelList.clear();
                        InventoryListBoxAdapter InventoryListBoxAdapter = new InventoryListBoxAdapter(RawMaterialSpotCheckActivity.this,QMSInventoryDetailsModelList);
                        lvList.setAdapter(InventoryListBoxAdapter);
                        stvBoxNo.setText("");
                        ActualScanNumber = 0;
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvSamplingPersonnel.setText("");
                        stvBoxNo.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(RawMaterialSpotCheckActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(RawMaterialSpotCheckActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }




    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}